<script lang="ts" setup>
import { useDictOptions } from '@/hooks'

const props = withDefaults(defineProps<Props>(), {
  classYear: undefined,
  term: undefined,
})

const emit = defineEmits(['update:classYear', 'update:term'])

interface Props {
  classYear?: number
  term?: string
}

const attrs = useAttrs()

const defaultValue = ref()
const options = ref<any[]>()
const getOptionList = async () => {
  const list: any[] = []
  const termOptions = useDictOptions('TermEnum').map((item) => {
    return {
      value: item.value,
      label: item.label,
    }
  })
  const currentYear = new Date().getFullYear()
  for (let i = -2; i <= 2; i++) {
    list.push({
      value: currentYear + i,
      label: `${currentYear + i}`,
      children: termOptions,
    })
  }
  options.value = list
}

const onGet = () => {
  if (!props.classYear && !props.term) {
    return undefined
  } else if (props.classYear && !props.term) {
    return [props.classYear]
  } else {
    return [props.classYear, props.term]
  }
}

const onSet = (value) => {
  if (!value) {
    emit('update:classYear', undefined)
    emit('update:term', undefined)
    return
  }
  if (value && value.length === 1) {
    emit('update:classYear', value[0])
    emit('update:term', undefined)
    return
  }
  if (value && value.length === 2) {
    emit('update:classYear', value[0])
    emit('update:term', value[1])
  }
}

const value = computed({
  get: () => onGet(),
  set: value => onSet(value),
})

onMounted(() => {
  getOptionList()
})
</script>

<template>
  {{ defaultValue }}
  <a-cascader
    v-model="value"
    :options="options"
    v-bind="attrs"
    placeholder="年份/学期"
    allow-clear
    path-mode
    allow-search
  >
    />
  </a-cascader>
</template>

<style lang='less' scoped>
</style>
